// 定义一个接口来描述pump函数的选项
interface PumpOptions {
  onChunk?: (chunk: Uint8Array) => void;
  onDone?: () => void;
}

// pump函数，使用解构来直接处理选项
async function pump(
  reader: ReadableStreamDefaultReader<Uint8Array>,
  controller: ReadableStreamDefaultController,
  options: PumpOptions = {}
): Promise<void> {
  try {
    let shouldContinue = true
    while (shouldContinue) {
      const { done, value } = await reader.read()
      if (done) {
        options.onDone?.()
        controller.close()
        shouldContinue = false
      } else {
        options.onChunk?.(value)
        controller.enqueue(value)
      }
    }

  } catch (error) {
    controller.error(error)
  }
}

// 重构fetchStream函数，采用解构来简化参数处理
export function fetchStream(
  response: Response,
  options: PumpOptions = {}
): ReadableStream<Uint8Array> {
  const reader = response.body!.getReader()
  return new ReadableStream({
    start: (controller) => pump(reader, controller, options)
  })
}
